package com.jt.common.thread;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

public class SyncTest {
    private static List<String> cache = new CopyOnWriteArrayList<>();
    public static List<String> selectAll(){
        /**
         * 双重校验锁机制
         * 当线程第一次进来的时候为空就执行下面的锁代码块
         * 当第二次进来的时候已经在内存中有缓存了，就不需要在进入同步锁代码块了
         * 及解决了线程安全也解决了并发
         */
       if(cache.isEmpty()){
           synchronized (cache){
               if(cache.isEmpty()){
                   System.out.println("Get Data From Database");
                   List<String> data = Arrays.asList("A","B","C");
                   cache.addAll(data);
               }
           }
       }
        return cache;
    }
    public static void main(String[] args) {
        Thread t1 = new Thread(){
            @Override
            public void run() {
                System.out.println(selectAll());
            }
        };
        Thread t2 = new Thread(){
            @Override
            public void run() {
                System.out.println(selectAll());
            }
        };
        Thread t3 = new Thread(){
            @Override
            public void run() {
                System.out.println(selectAll());
            }
        };
        Thread t4 = new Thread(){
            @Override
            public void run() {
                System.out.println(selectAll());
            }
        };
        Thread t5 = new Thread(){
            @Override
            public void run() {
                System.out.println(selectAll());
            }
        };
        t1.start();
        t2.start();
        t3.start();
        t4.start();
        t5.start();
    }
}
